import React, { useEffect, useState } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import {
    Button,
    Form,
    Input,
    InputNumber,
    Switch,
    Upload,
    message,
    Select,
    DatePicker,
    ConfigProvider,
    Radio,
    Row,
    Col
} from 'antd';
import locale from 'antd/locale/zh_CN';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';

axios.defaults.baseURL = 'http://localhost:3000/';
dayjs.locale('zh-cn');

const style = {
    display: 'flex',
    flexDirection: 'column',
    gap: 8,
};
const { RangePicker } = DatePicker;

const normFile = (e) => {
    if (Array.isArray(e)) {
        return e;
    }
    return e?.fileList;
};

const Space = () => {
    const [value, setValue] = useState(1);
    const [selectedValue, setSelectedValue] = useState(undefined);
    let [status, setstatus] = useState([]);
    const [dateRange, setDateRange] = useState([]);
    const [publishDate, setPublishDate] = useState(null);

    const onChange = (date, dateString) => {
        console.log(date, dateString);
        if (value === 2) {
            setPublishDate(date);
        }
    };

    const onChanges = (e) => {
        setValue(e.target.value);
    };

    const handleDateChange = (dates) => {
        setDateRange(dates);
    };

    const getstatus = async () => {
        const { data: { list } } = await axios.get('/kai/getstatus');
        const formattedOptions = list.map(item => ({
            value: item._id,
            label: item.value
        }));
        setstatus(formattedOptions);
    };

    const navigator = useNavigate();
    const [formData, setFormData] = useState({
        title: '',
        titl: '',
        image: [],
        sequence: null,
        status: false
    });

    const handleInputChange = (e) => {
        const { name, value } = e.target;
        setFormData(prevData => ({
            ...prevData,
            [name]: value
        }));
    };

    const handleFileChange = (e) => {
        setFormData(prevData => ({
            ...prevData,
            image: normFile(e)
        }));
    };

    const handleChanges = (value) => {
        setSelectedValue(value);
    };

    const handleSave = async () => {
        try {
            let imageUrl = '';
            if (formData.image && formData.image.length > 0) {
                const file = formData.image[0].originFileObj;
                const formDataToSend = new FormData();
                formDataToSend.append('file', file);
                const uploadResponse = await axios.post('/kai/uploads', formDataToSend);
                imageUrl = uploadResponse.data.path;
            }

            let tidValue;
            if (value === 1) {
                tidValue = '2'; // 立即发布，已发布状态
            } else if (value === 2 && publishDate) {
                if (dayjs(publishDate).isBefore(dayjs())) {
                    tidValue = '2'; // 定时发布时间早于当前时间，已发布状态
                } else {
                    tidValue = '1'; // 定时发布时间晚于当前时间，进行中状态
                }
            } else {
                tidValue = '0'; // 默认状态
            }
            let tidd;
            if (tidValue === '2') {
                tidd = '67b3393dc252fab183d9b810';
            }else{
                tidd = '67b33937c252fab183d9b80e';
            }

            const dataToSend = {
                name: formData.title,
                di: formData.titl,
                sid: selectedValue,
                startTime: dateRange[0] ? dayjs(dateRange[0]).toISOString() : null,
                endTime: dateRange[1] ? dayjs(dateRange[1]).toISOString() : null,
                end_time: formData.deadline ? dayjs(formData.deadline).toISOString() : null,
                img: imageUrl,
                tid: tidd,
                xin: '桂花小区摄影大赛火热进行中'
            };

            await axios.post('/kai/addactive', dataToSend, {
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            message.success('数据添加成功');
            navigator(-1);
        } catch (error) {
            message.error('数据添加失败');
            console.error('数据添加失败', error);
        }
    };

    useEffect(() => {
        getstatus();
    }, []);

    return (
        <div
            style={{
                scrollbarWidth: 'none',
                overflowY: 'auto',
                margin: 'auto',
                width: '70%',
                height: '100%',
            }}
        >
            <div
                style={{
                    marginTop: '0.6rem',
                    overflow: 'hidden',
                    backgroundColor: 'white',
                    width: '100%',
                    height: '80%',
                    borderRadius: '20px',
                }}
            >
                <div style={{ display: 'flex', margin: '0.6rem' }}>
                    <div
                        style={{
                            width: '0.16rem',
                            marginTop: '0.1rem',
                            borderRadius: '0.1rem',
                            height: '0.6rem',
                            backgroundColor: '#3dd4a7',
                        }}
                    ></div>
                    <div style={{ fontSize: '0.5rem', marginLeft: '0.2rem' }}>新增活动</div>
                </div>
                <div>
                    <Form
                        labelCol={{
                            span: 6,
                        }}
                        wrapperCol={{
                            span: 18,
                        }}
                        layout="horizontal"
                        style={{
                            maxWidth: '100%',
                        }}
                    >
                        <Row gutter={30} align="middle">
                            <Col span={12}>
                                <Form.Item label="活动标题" style={{ marginLeft: '-1rem' }}>
                                    <Input
                                        style={{ width: '10rem', height: '1rem' }}
                                        name="title"
                                        value={formData.title}
                                        onChange={handleInputChange}
                                    />
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="分类" style={{ marginLeft: '0rem' }}>
                                    <Select
                                        placeholder="请选择"
                                        defaultValue={selectedValue}
                                        style={{
                                            width: 220,
                                            height: '1rem',
                                        }}
                                        onChange={handleChanges}
                                        options={status}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Form.Item label="图片" style={{ marginLeft: '-6rem' }}>
                            <Upload
                                listType="picture-card"
                                onChange={handleFileChange}
                                fileList={formData.image}
                            >
                                <button
                                    style={{
                                        border: 0,
                                        background: 'none',
                                    }}
                                    type="button"
                                >
                                    <PlusOutlined />
                                    <div
                                        style={{
                                            marginTop: 8,
                                        }}
                                    >
                                        Upload
                                    </div>
                                </button>
                            </Upload>
                        </Form.Item>
                        <Row gutter={16} align="middle">
                            <Col span={12}>
                                <Form.Item label="活动日期" style={{ marginLeft: '-1rem' }}>
                                    <ConfigProvider locale={locale}>
                                        <RangePicker
                                            onChange={handleDateChange}
                                            style={{ width: '6rem', height: '1rem' }}
                                        />
                                    </ConfigProvider>
                                </Form.Item>
                            </Col>
                            <Col span={12}>
                                <Form.Item label="活动地点" style={{ marginLeft: '-6rem' }}>
                                    <Input
                                        style={{ width: '10rem', height: '1rem' }}
                                        name="titl"
                                        value={formData.titl}
                                        onChange={handleInputChange}
                                    />
                                </Form.Item>
                            </Col>
                        </Row>
                        <Form.Item label="报名截止日期" style={{ marginLeft: '-6rem' }}>
                            <ConfigProvider locale={locale}>
                                <DatePicker
                                    onChange={(date, dateString) => {
                                        onChange(date, dateString);
                                        setFormData(prevData => ({
                                            ...prevData,
                                            deadline: date
                                        }));
                                    }}
                                    style={{ width: '6rem', height: '1rem' }}
                                />
                            </ConfigProvider>
                        </Form.Item>
                        <Form.Item label="发布时间" style={{ marginLeft: '-6rem' }}>
                            <Row align="middle" gutter={16}>
                                <Col span={12}>
                                    <Radio.Group
                                        style={style}
                                        onChange={onChanges}
                                        value={value}
                                        options={[
                                            {
                                                value: 1,
                                                label: '立即发布',
                                            },
                                            {
                                                value: 2,
                                                label: '定时发布',
                                            },
                                        ]}
                                    />
                                </Col>
                                <Col span={12}>
                                    {value === 2 && (
                                        <ConfigProvider locale={locale}>
                                            <DatePicker
                                                onChange={onChange}
                                                style={{ width: '6rem', height: '1rem' }}
                                            />
                                        </ConfigProvider>
                                    )}
                                </Col>
                            </Row>
                        </Form.Item>
                        <Form.Item wrapperCol={{ offset: 6, span: 18 }} style={{ marginTop: '2rem', marginLeft: '-6rem' }}>
                            <Button
                                style={{ background: '#5adbb5', width: '2rem', height: '1rem' }}
                                type="primary"
                                onClick={handleSave}
                            >
                                保存
                            </Button>
                            <Button
                                style={{ marginLeft: '1rem', width: '2rem', height: '1rem' }}
                                onClick={() => {
                                    navigator(-1);
                                }}
                                color="default"
                                variant="outlined"
                            >
                                返回
                            </Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </div>
    );
};

export default Space;